`timescale 1ns / 1ps 
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module DEBOUNCE_IN #(
    parameter PIN_INIT   = 1'b1
)
(
    input  clk,
    
    input  pin_in,
    output pin_out,

    output pin_pos,
    output pin_neg,
    
    input  rst_n
);
//===============================================================================
reg reset = 1;
always @ (posedge clk)
    reset <= ~rst_n;

reg [7:0] pin_filter = {8{PIN_INIT}};
always @ (posedge clk)
if(reset) pin_filter <= {8{PIN_INIT}};
else pin_filter <= {pin_filter[6:0], pin_in};

reg pin_r = PIN_INIT;
always @ (posedge clk)
if(reset) pin_r <= PIN_INIT;
else 
begin
    if(&pin_filter) pin_r <= 1;
    if(~|pin_filter) pin_r <= 0;
end

reg [1:0] pin_state = {2{PIN_INIT}};
always @ (posedge clk)
if(reset) pin_state <= {2{PIN_INIT}};
else
    pin_state <= {pin_state[0], pin_r};
    

assign pin_out = pin_r;
assign pin_pos = (pin_state == 2'b01) ? 1'b1 : 1'b0;
assign pin_neg = (pin_state == 2'b10) ? 1'b1 : 1'b0;
//===============================================================================

endmodule
